// 我参与的会议
<template>
  <layoutDividerPage class="attended">
    <template #search>
      <vxe-form
        title-align="right"
        title-width="100"
        class-name="custom-form"
        :data="formSearch"
        @submit="handleSearch"
        @reset="handleReset"
      >
        <vxe-form-item
          title="会议状态："
          field="status"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select
              v-model="formSearch.status"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in _discStore.getDictType('meeting_status')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="我的参加状态："
          field="participationStatus"
          span="6"
          :item-render="{}"
          title-width="120"
        >
          <template #default>
            <el-select
              v-model="formSearch.participationStatus"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in _discStore.getDictType(
                  'meeting_participation_status'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="结论状态："
          field="conclusionStatus"
          span="6"
          :item-render="{}"
          title-width="120"
        >
          <template #default>
            <el-select
              v-model="formSearch.conclusionStatus"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in _discStore.getDictType('conclusion_status')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="会议开始时间："
          field="startTime"
          title-width="120"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-date-picker
              v-model="formSearch.startTime"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="会议类型："
          field="meetingType"
          span="6"
          :item-render="{}"
        >
          <template #default>
            <el-select v-model="formSearch.meetingType" placeholder="请选择">
              <el-option label="不限" value="" />
              <el-option
                v-for="item in _discStore.getDictType('meeting_type')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </vxe-form-item>
        <vxe-form-item
          title="关键字："
          field="keyName"
          span="12"
          :item-render="{}"
        >
          <template #default>
            <div class="keyWord">
              <el-select
                v-model="formSearch.keyName"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in keyWordsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="formSearch.keyValue"
                placeholder="请输入"
                clearable
              />
            </div>
          </template>
        </vxe-form-item>
        <vxe-form-item span="6" align="right" class-name="custom-form-button">
          <template #default>
            <el-button native-type="submit" type="primary">搜索</el-button>
            <el-button native-type="reset">重置</el-button>
          </template>
        </vxe-form-item>
      </vxe-form>
    </template>
    <vxe-grid
      ref="xGrid"
      border
      stripe
      keep-source
      auto-resize
      sync-resize
      :loading="listLoading"
      :column-config="{ resizable: true }"
      :export-config="{}"
      :columns="tableColumn"
      show-overflow="tooltip"
      align="left"
      :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
    >
      <template #form>
        <div class="button-list">
          <el-button :loading="downLoading" plain @click="handleExport">
            导出搜索结果
          </el-button>
        </div>
      </template>
      <template #participationStatus="{ row }">
        <el-text :type="participantStatus(row.participationStatus).colorType">
          {{ participantStatus(row.participationStatus).label }}
        </el-text>
      </template>
      <template #options="{ row }">
        <el-button type="primary" link @click="handleDetails(row)">
          详情
        </el-button>
        <el-button
          v-if="row.participationStatus === '1'"
          type="success"
          link
          @click="handleAccept(row)"
        >
          接受
        </el-button>
        <el-button
          v-if="row.participationStatus === '1'"
          type="danger"
          link
          @click="handleReject(row)"
        >
          拒绝
        </el-button>
      </template>
      <template #bottom>
        <el-pagination
          background
          :current-page="formSearch.pageNo"
          layout="total, sizes, prev, pager, next, jumper"
          :page-size="formSearch.pageSize"
          :total="formSearch.total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </template>
    </vxe-grid>
  </layoutDividerPage>
</template>

<script lang="ts" setup>
  import layoutDividerPage from '@/components/layoutDividerPage.vue'
  import { useDownload } from '@/utils/useDownload'
  import { formatMinutes } from '@/utils/index'
  import {
    formSearchAttendedProps,
    optionsProps,
    pagingProps,
    rowAttendedProps,
    resPageAttendedProps,
    resProps,
  } from '../../interface'
  import {
    getMeetingsMyParticipationPage,
    getMeetingsExportExcel,
    getMeetingsUpdateParticipantStatus,
  } from '@/api/project/meeting'
  import { useDictStore } from '@/store/modules/dict'
  const _discStore = useDictStore()

  const tableColumn = [
    { title: '会议ID', field: 'id', minWidth: 80 },
    { title: '会议主题', field: 'meetingTopic', minWidth: 120 },
    {
      title: '会议开始时间',
      field: 'startTime',
      minWidth: 120,
      formatter: ['formatDate', 'yyyy-MM-dd HH:mm:ss'],
    },
    {
      title: '预估会议时长',
      field: 'estimatedDuration',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return formatMinutes(cellValue)
      },
    },
    { title: '会议地点', field: 'location', minWidth: 120 },
    { title: '组织人', field: 'creatorName', minWidth: 120 },
    {
      title: '会议类型',
      field: 'meetingType',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('meeting_type', cellValue)
      },
    },
    { title: '会议描述', field: 'description', minWidth: 120 },
    {
      title: '会议状态',
      field: 'status',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('meeting_status', cellValue)
      },
    },
    {
      title: '结论状态',
      field: 'conclusionStatus',
      minWidth: 120,
      formatter: ({ cellValue }) => {
        return _discStore.getDictLabelForValue('conclusion_status', cellValue)
      },
    },
    {
      title: '是否参会反馈',
      field: 'participationStatus',
      minWidth: 120,
      slots: { default: 'participationStatus' },
      // formatter: ({ cellValue }) => {
      //   return _discStore.getDictLabelForValue(
      //     'meeting_participation_status',
      //     cellValue
      //   )
      // },
    },
    {
      title: '操作',
      field: 'options',
      minWidth: 160,
      slots: { default: 'options' },
    },
  ]
  // 关键字变量
  const keyWordsOptions: optionsProps[] = [
    {
      label: '会议主题',
      value: 'meetingTopic',
    },
    {
      label: '会议描述',
      value: 'description',
    },
  ]

  // 参会人员状态属性
  const participantStatus: any = computed(() => {
    return (value: string) =>
      _discStore.getDictForValue('meeting_participation_status', value) || {
        colorType: 'info',
        label: '待定',
      }
  })

  // 表格实例
  const xGrid = ref(null)
  // 加载状态
  const listLoading = ref<boolean>(false)
  // 查询表单
  const formSearch = reactive<Partial<formSearchAttendedProps> & pagingProps>({
    pageNo: 1,
    pageSize: 10,
    total: 0,
  })

  // 搜索关键字处理
  const handleKeyWords = () => {
    const { keyName, keyValue, ...otherParams } = formSearch

    const searchParams = keyName
      ? { ...otherParams, [keyName]: keyValue }
      : { ...otherParams }

    return searchParams
  }

  // 搜索
  const handleSearch = async () => {
    try {
      listLoading.value = true
      const searchParams = handleKeyWords()
      const res: resPageAttendedProps =
        await getMeetingsMyParticipationPage(searchParams)
      if (res && res.code === 0 && res.data) {
        xGrid.value.reloadData(res.data?.list || [])
        formSearch.total = res.data?.total
      } else {
        xGrid.value.reloadData([])
      }
    } catch (e) {
      console.error('获取我参与会议列表时出错:', e)
      xGrid.value.reloadData([])
    } finally {
      listLoading.value = false
    }
  }
  // 重置
  const handleReset = () => {
    formSearch.pageNo = 1
    formSearch.pageSize = 10
    formSearch.total = 0
    formSearch.keyValue = ''
    handleSearch()
  }

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    formSearch.pageSize = val
    handleSearch()
  }

  // 当前页变化
  const handleCurrentChange = (val: number) => {
    formSearch.pageNo = val
    handleSearch()
  }

  onMounted(() => {
    handleSearch()
  })

  // 接受
  const handleAccept = (row: rowAttendedProps) => {
    ElMessageBox.confirm(`确定接受${row.creatorName}的会议邀请?`, '接受', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const params = {
        meetingId: row.id,
        participantStatus: '2',
      }
      const res: resProps = await getMeetingsUpdateParticipantStatus(params)
      console.log('res', res.code === 0)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '接受成功',
        })
      }
      handleReset()
    })
    // .catch(() => {
    //   ElMessage({
    //     type: 'info',
    //     message: '取消操作',
    //   })
    // })
  }

  // 拒绝
  const handleReject = (row: rowAttendedProps) => {
    ElMessageBox.confirm(`确定拒绝${row.creatorName}的会议邀请?`, '拒绝', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const params = {
        meetingId: row.id,
        participantStatus: '3',
      }
      const res: resProps = await getMeetingsUpdateParticipantStatus(params)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '拒绝成功',
        })
      }
      handleReset()
    })
    // .catch(() => {
    //   ElMessage({
    //     type: 'info',
    //     message: '取消操作',
    //   })
    // })
  }

  // 导出搜索结果
  const { downLoading, downloadFile } = useDownload(
    getMeetingsExportExcel,
    '我参与的会议列表.xls'
  )

  const handleExport = async () => {
    const searchParams = handleKeyWords()
    const params = {
      ...searchParams,
      exportType: 1,
    }
    await downloadFile(params)
  }

  // 路由实例
  const router = useRouter()
  // 明细
  const handleDetails = (row: rowAttendedProps) => {
    router.push({
      name: 'Meetings_Details',
      query: { id: row.id },
    })
  }
</script>

<style lang="scss" scoped>
  .attended {
    .button-list {
      display: flex;
      align-items: center;
      justify-content: end;
      margin: 20px 0;
    }

    .keyWord {
      display: flex;
      align-items: center;
      width: 100%;

      .el-select {
        width: 30%;
      }

      .el-input {
        margin-left: 10px;
      }
    }
  }
</style>
